﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using NReader.Common;
using NReader.Service;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace NReader
{
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    public class BookTranChapterInfo : object, System.ComponentModel.INotifyPropertyChanged
    {
        public NReader.Service.RAS.ChapterInfo CurrentChapter { get; set; }

        public IList<NReader.Service.RAS.ChapterInfo> MaxChapters { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class Book : NReader.Common.LayoutAwarePage
    {
        private IList<NReader.Service.RAS.ChapterInfo> _maxChapters;

        public Book()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var articleid = (int) navigationParameter;
            var article = await ArticleService.Instance().GetArticle(articleid);
            this.DefaultViewModel["Article"] = article;
            if (!string.IsNullOrEmpty(article.coverlink))
            {
                DataBindingCover("http://www.kkkxs.com/files/article/image/20/20993/20993s.jpg",//article.coverlink,
                                 string.Format(@"Microsoft\\WindowsStore\\ApiData\\Cover\\{0}.jpg", article.articleid));
            }
            var list = await ArticleService.Instance().GetMaxChapterList(articleid);
            this.DefaultViewModel["Chapters"] = list;
            _maxChapters = list;
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void ItemGridViewItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                var chapter = ((NReader.Service.RAS.ChapterInfo) e.ClickedItem);
                var tran = new BookTranChapterInfo {CurrentChapter = chapter};
                if (_maxChapters != null)
                    tran.MaxChapters = _maxChapters;

                this.Frame.Navigate(typeof (Chapter), tran);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        public async void DataBindingCover(string url, string path)
        {
            try
            {
                var file = await GetCover(url, path);
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(stream);
                    imgCover.Source = bitmapImage;
                }
            }
            catch (Exception ex)
            {
                //throw;
            }
        }

        private async Task<Windows.Storage.StorageFile> GetCover(string url, string path)
        {
            StorageFolder folder = await
                                 ApplicationData.Current.LocalFolder.CreateFolderAsync(
                                     System.IO.Path.GetDirectoryName(path),
                                     CreationCollisionOption.OpenIfExists);
            bool exist = true;
            try
            {
                Windows.Storage.StorageFile file = await folder.GetFileAsync(System.IO.Path.GetFileName(path));
                return file;
            }
            catch (Exception)
            {
                exist = false;
            }
            if (!exist)
            {
                var client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Windows.Storage.StorageFile file =
                        await
                        folder.CreateFileAsync(System.IO.Path.GetFileName(path), CreationCollisionOption.ReplaceExisting);
                    await FileIO.WriteBytesAsync(file, await response.Content.ReadAsByteArrayAsync());
                    return file;
                }
            }
            return null;
        }

    }
}
